<template>
  <div>
    <!-- 顶部的面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-s-promotion"></i> 后台管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/' }">菜单</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: './' }">菜品管理</el-breadcrumb-item>
      <el-breadcrumb-item>新增菜品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <!-- 表单 -->
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
      <el-form-item label="菜品种类" prop="categoryId">
        <el-select v-model="ruleForm.categoryId" placeholder="请选择">
          <el-option
              v-for="item in dishCategoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="菜品名称" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>

      <el-form-item label="价格" prop="price">
        <el-input v-model="ruleForm.price"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="ruleForm.description"></el-input>
      </el-form-item>
      <el-form-item label="菜品图片" prop="image">
        <el-upload
            class="picture-uploader"
            action="http://localhost:9523/resources/upload/image/dish"
            :show-file-list="false"
            :on-success="handleUploadSuccess">
          <i class="el-icon-upload picture-uploader-icon"></i>
          <div class="picture-uploader-text">仅允许上传 <i>JPG</i> / <i>PNG</i> 格式的图片</div>
          <div class="picture-uploader-text">仅允许上传不超过 <i>5MB</i> 的图片</div>
        </el-upload>
      </el-form-item>

      <el-form-item label="是否启用">
        <el-switch
            v-model="ruleForm.enable"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ccc">
        </el-switch>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button type="warning" @click="gotoList">返回列表</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 菜品种类的下拉菜单的选择列表
      dishCategoryOptions: [],
      // 表单
      ruleForm: {
        categoryId: 1,
        name: '测试菜品',
        price: 23.22,
        description: '好吃到爆!',
        image: '',
        enable: 1
      },
      // 表单规则
      rules: {
        categoryId: [
          {required: true, message: '请选择菜品种类', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入菜品名称', trigger: 'blur'},
          {
            pattern: /^[a-zA-Z\u4e00-\u9fa5]{2,10}$/,
            message: '菜品必须是2~10长度的字符组成，且不允许使用标点符号',
            trigger: 'blur'
          }
        ],
        price: [
          {required: true, message: '请输入菜品价格', trigger: 'blur'},
        ],
        description: [
          {required: true, message: '请输入菜品描述', trigger: 'blur'},
        ],
        image: [
          {required: true, message: '请输入菜品图片', trigger: 'blur'},
        ]
      }
    };
  },
  methods: {
    // 返回列表
    gotoList() {
      this.$router.push('/admin/menu/dish');
    },
    // 加载菜品种类列表
    loadDishCategoryList() {
      let url = 'http://localhost:9523/menu/dishCategory/list?queryType=all';
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.dishCategoryOptions = jsonResult.data.list;
          if (this.dishCategoryOptions && this.dishCategoryOptions[0]) {
            this.ruleForm.categoryId = this.dishCategoryOptions[0].id;
          }
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },

    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:9523/menu/dish/add-new';
          console.log('url = ' + url);
          let formData = this.qs.stringify(this.ruleForm);
          console.log('formData = ' + formData);

          this.axios
              .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
              .post(url, formData).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state == 20000) {
              this.$message({
                message: '新增菜品成功！',
                type: 'success'
              });
              this.resetForm(formName);
            } else {
              let title = '操作失败';
              this.$alert(jsonResult.message, title, {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          }).catch(error => {
            let title = '错误';
            let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
            this.$alert(message, title, {
              confirmButtonText: '确定',
              callback: action => {
              }
            });
            console.log(error);
          });
        } else {
          console.log('请求参数格式错误！');
          return false;
        }
      });
    },
    // 上传成功后的回调
    handleUploadSuccess(response) {
      console.log("response" + response);
      this.editForm.image = response.data.url;
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.loadDishCategoryList();
  }
}
</script>

<style>
.picture-uploader {
  float: left;
  width: 240px;
  height: 135px;
  margin-right: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.picture-uploader .picture-uploader-icon {
  width: 240px;
  height: 80px;
  font-size: 58px;
  color: #8c939d;
  line-height: 80px;
  text-align: center;
}

.picture-uploader .picture-uploader-text {
  width: 240px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  font-size: 10px;
  color: #8c939d;
}

.picture-uploader .picture-uploader-text i {
  font-size: 10px;
  font-weight: bold;
  font-style: normal;
  color: #F56C6C;
}

.picture-preview {
  width: 240px;
  height: 135px;
  margin-right: 20px;
  border: 1px solid #e8e6e6;
  border-radius: 6px;
  float: left;
  display: inline;
  position: relative;
}

.picture-preview .image {
  width: 240px;
  height: 135px;
  border-radius: 6px;
}
</style>
